package com.example.simplecrud.controller;

import com.example.simplecrud.model.User;
import com.example.simplecrud.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public String getAllUsers(Model model) {
        model.addAttribute("users", userRepository.findAll());
        return "index";
    }

    @GetMapping("/new")
    public String newUser(User user) {
        return "new";
    }

    @PostMapping
    public String createUser(User user) {
        userRepository.save(user);
        return "redirect:/users";
    }

    @GetMapping("/{id}/edit")
    public String getUserById(@PathVariable Integer id, Model model) {
        Optional<User> user = userRepository.findById(id);
        model.addAttribute("user", user.orElse(new User()));
        return "edit";
    }

    @PostMapping("/{id}/update")
    public String updateUser(@PathVariable Integer id, User user) {
        user.setId(id);
        userRepository.save(user);
        return "redirect:/users";
    }

    @PostMapping("/{id}/delete")
    public String deleteUser(@PathVariable Integer id) {
        try {
            userRepository.deleteById(id);
        } catch (Exception e) {
            // 忽略删除失败的异常
        }
        return "redirect:/users";
    }
}
